<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of system_controller
 *
 * @author phamhphuc
 */
class system_controller {
    //put your code here
    public $isAdmin = false;
    protected static $_instance = null;
    public $config;
    public $action = "index";
    public $isUseLayout = true;
    public $layoutName = "default";
    public $forwardAction = "";
    public $settings = array();
    public $frontendsetup = array();
    public $contestsetup = array();
    public $fb_page_data = false;
    public $lang = array();
    public $licence = array();
    /**
     *
     * @var system_view
     */
    public $view = null;
    /**
     *
     * @var system_session
     */
    public $session = null;
    /**
     *
     * @var system_db
     */
    public $db;
    /**
     *
     * @var array
     */
    public $userdata = false;

    public function __construct($config) {
        $this->config = $config;
        if(isset($config['default_action'])) {
            $this->action = $config['default_action'];
        }
        $this->view = new system_view();
        $this->db = new system_db($config);
        $this->session = new system_session($config);
        $this->_setupData();
        $this->setupSettings();
        $this->init();
    }

    public function init()
    {

        // check licence
        if($this->licence['is_disabled'] && (!$this->isAdmin)){
            die("This account is disabled!!!");
        }

        $defaultLanguageCode = "no";
        $this->config['language'] = $defaultLanguageCode;
        $langFile = "../../lang/{$this->config['language']}.php";
        if(is_file($langFile)){
            $this->lang = include $langFile;
        }
        if(isset($this->userdata['langs'][$this->config['language']])) {
            $newlangs = $this->userdata['langs'][$this->config['language']];
            $this->lang = array_merge($this->lang, $newlangs);
        }
        $this->view->setLanguageArray($this->lang);
        $this->view->config = $this->config;
        
        $url = "http://" . $_SERVER['HTTP_HOST'] . dirname($_SERVER['PHP_SELF']) . "/";
        
        if(substr($this->settings['facebook_share_image_url'], 0,4) != "http") {
            $this->settings['facebook_share_image_url'] = $url . $this->settings['facebook_share_image_url'];
        }

        $this->view->settings = $this->settings;
        $this->view->frontendsetup = $this->frontendsetup;
        $this->view->contestsetup = $this->contestsetup;

    }

    protected function setlayout($layoutName) {
        $this->layoutName = $layoutName;
    }

    public function _filterTextArr($data, $editorFields = array()){
        // require html filter engine
        require_once 'htmlfilter/HTMLPurifier.auto.php';
        $config = HTMLPurifier_Config::createDefault();                
//        $config->set('HTML.Trusted', true);
        $config->set('Filter.YouTube', true);
//        $config->set('HTML.DefinitionID', '1');
//        $config->set('HTML.SafeObject', 'true');
        $config->set('Output.FlashCompat', 'true');
        $config->set('HTML.FlashAllowFullScreen', 'true');
        $config->set('HTML.SafeIframe', true);
        $config->set('URI.SafeIframeRegexp', '%^http://(www.youtube(?:-nocookie)?.com/embed/|player.vimeo.com/video/)%');
        
        $purifier = new HTMLPurifier($config);   
        foreach($data as $k => &$v){
            if(in_array($k, $editorFields)) {
                $search = array('\\"', '"','\\\\', "\\'");
                $replace = array('"', "'","","'");
                $v = str_replace($search, $replace, $v);
            } else {
                $search = array("'", '"', '\\');
                $replace = array("`", "”", '');
                $v = str_replace($search, $replace, $v);
            }
            $v = $purifier->purify($v);
        }
        return $data;
    }

    public function handle()
    {
        if(isset($_REQUEST['action'])) {
            $this->action = $_REQUEST['action'];
        }

        $content = "";

        $actionName = $this->action . "Action";
        $content = $this->_callAction($actionName);

        if($this->isUseLayout) {

            $data = $this->view->getData();

            $data['view_content'] = $content;
            $this->view->view_content = $content;

            $data = (object)$data;

            $data = array(
                'view' => $this->view
            );

            $html = $this->get_include_contents("{$this->config['template_dir']}layouts/{$this->layoutName}.php", $data);
            echo $html;
        } else {
            echo $content;
        }
    }


    protected function _forward($actionName) {
        $this->forwardAction = $actionName;
    }


    public function _callAction($actionName) {
        $this->$actionName();
        $this->view->action = $this->action;
        if($this->forwardAction != "") {
            $this->action = $this->forwardAction;
            $this->forwardAction = "";
            $actionName = $this->action . "Action";
            $this->$actionName();
            $this->view->action = $this->action;
        }
        $data = $this->view->getData();

        $data['action'] = $this->action;

        $data = (object)$data;
        $data = array(
            'view' => $this->view
        );
        $viewName = str_replace("Action", "", $actionName);

        $content = $this->get_include_contents("{$this->config['template_dir']}views/{$viewName}.php", $data);
        return $content;
    }

    public function getTemplateDir(){
        if($this->config['template_name']) {
            return "../../templates/{$this->config['template_name']}/";
        }
        return "";
    }

    public function getTemplateURL(){
        if($this->config['template_name']) {
            if($this->config['use_aws_template_storage']){
                return "{$this->config['aws_template_url']}{$this->config['template_name']}/";
            }
            return "../../templates/{$this->config['template_name']}/";
        }
        return "";
    }

    public static function getInstance() {
        if (null === self::$_instance) {
            self::$_instance = new self ();
        }
        return self::$_instance;
    }

    public function _setNoLayout()
    {
        $this->isUseLayout = false;
    }

    public function get_include_contents($filename , $data = '') {
        if(!is_file($filename)){
            $filename = str_replace("templates/{$this->config['template_name']}/", "templates/calendar/", $filename);
        }
        if (is_file($filename)) {
            if (is_array($data)) {
                extract($data);
            }
            ob_start();
            include $filename;
            $contents = ob_get_contents();
            ob_end_clean();
            return $contents;
        } else {
            die($filename . " doesn't exists");
        }
    }

    public function _setupData()
    {
        // detect user from uid param
        if(isset($_REQUEST['uid'])){
            $this->config['user_id'] = $_REQUEST['uid'];
            $key = @$_REQUEST['key'];
            if($key != md5($this->config['secret_key'] . $this->config['user_id'])){
                header("location: ?action=notsetup");die;
            }
        }
        // detect user from facebook page
        if($this->config['facebookstatus']){
            $pageid = $this->config['facebookstatus']['page']['id'];
            //find user match with this page from system
            $userID = $this->db->getOne("select user_id from #__admin_user where fb_page_id = '{$pageid}'");
            if($userID){
                $this->config['user_id'] = $userID;
            } else {
                if($_REQUEST['action'] != "notsetup"){
                    header("location: ?action=notsetup");die;
                }
            }
        }
        $uid = mysql_escape_string($this->config['user_id']);
        // set up user data
        $userData = $this->db->getRow("select * from #__admin_user where user_id = '{$uid}'");
        if(!$userData) {
            if(($_REQUEST['action'] != "notsetup")  && (!$this->isAdmin)){
                header("location: ?action=notsetup");die;
            }
        } else {
            if($userData['langs'] != "") {
                $userData['langs'] = unserialize($userData['langs']);
            }
            if($userData['general_setting'] != "") {
                $userData['general_setting'] = unserialize($userData['general_setting']);
            }
            if($userData['contest_setup'] != "") {
                $userData['contest_setup'] = unserialize($userData['contest_setup']);
            }
            if($userData['frontend_setup'] != "") {
                $userData['frontend_setup'] = unserialize($userData['frontend_setup']);
            }
            if($userData['fb_page_data'] != "") {
                $userData['fb_page_data'] = unserialize($userData['fb_page_data']);
            }
            $this->userdata = $userData;
        }
        $this->config['key'] = md5($this->config['secret_key'] . $this->config['user_id']);
        $this->view->key = $this->config['key'];

        // set up sharetab URL
        $path = pathinfo($_SERVER['PHP_SELF']);
        $facebooktab_share_url = "http://" . $_SERVER['HTTP_HOST'] . $path['dirname'] . "/?action=fblikeview&uid={$this->config['user_id']}&key={$this->config['key']}";
        $this->config['facebooktab_share_url'] = $facebooktab_share_url;
//        echo $facebooktab_share_url;die;
    }

    protected function _frontredirect($action){
        $url = "?action={$action}&uid={$this->config['user_id']}&key={$this->config['key']}";
        header("location: {$url}");die;
    }

    public function updateSetting($key, $value){
        // check if the key is exist or not
        if(isset($this->settings[$key])){
            $this->db->update("#__setting", array('option_value' => serialize($value)), "option_key = '{$key}' and user_id ={$this->config['user_id']}");
        } else {
            $this->db->insert("#__setting", array('option_key' => $key,'option_value' => serialize($value), 'user_id' => $this->config['user_id']));
            echo mysql_error();
        }
        $this->settings[$key] = $value;
    }

    public function updateSettingForAllUsers($key, $value){
        return $this->db->update("#__setting", array('option_value' => serialize($value)), "option_key = '{$key}'");
    }

    public function getSetting($key){
        return $this->settings[$key];
    }

    public function reloadSettings()
    {
        $this->_setupData();
        $this->setupSettings();
    }

    public function setupSettings(){
        // load the system setting
        $settingFile = 'setting.php';
        if(!is_file($settingFile)) {
            $settingFile = "../" . $settingFile;
        }
        $systemSetting = include $settingFile;
        // merge with user setting
        if($this->userdata['general_setting']) {
            $systemSetting = array_merge($systemSetting, $this->userdata['general_setting']);
        }

        $this->settings = $systemSetting;

        // font end setup
        $frontendsetupFile = "fontendsetup.php";
        if(!is_file($frontendsetupFile)) {
            $frontendsetupFile = "../" . $frontendsetupFile;
        }
        $frontendsetup = include $frontendsetupFile;
        if($this->userdata['frontend_setup']) {
            $frontendsetup = array_merge($frontendsetup, $this->userdata['frontend_setup']);
        }
        $this->frontendsetup = $frontendsetup;

        // contest setup
        $contestsetupFile = "contestsetup.php";
        if(!is_file($contestsetupFile)) {
            $contestsetupFile = "../" . $contestsetupFile;
        }
        $contestsetup = include $contestsetupFile;
        if($this->userdata['contest_setup']) {
            $contestsetup = array_merge($contestsetup, $this->userdata['contest_setup']);
        }
        $this->contestsetup = $contestsetup;

        // set up page data
        $this->fb_page_data = $this->userdata['fb_page_data'];
        $this->view->fb_page_data = $this->fb_page_data;

        // set up licence data
        $this->licence = array(
            'level_id' => $this->userdata['level_id'],
            'expired_time' => $this->userdata['expired_time'],
            'is_disabled' => $this->userdata['is_disabled'],
            'access_type' => $this->userdata['access_type']
        );
        // check if licence is still valid

        if(!$this->isAdmin){
            if($this->licence['expired_time'] < time()) {
                $u = $this->updateUserLevel();
                if($u['expired_time'] < time()){
                    $this->licence['is_disabled'] = 1;
                } else {
                    $this->licence['is_disabled'] = 0;
                }
            }
        }


        if(!$this->isAdmin) {
            $this->config['template_name'] = $this->frontendsetup['select_template'];
        }

        $this->config['template_dir'] = $this->getTemplateDir();
        $this->config['template_url'] = $this->getTemplateURL();
    }

    public function updateUserLevel($uid = false){
        if(!$uid) {
            $uid = $this->config['user_id'];
        }
        // get user out
        $user = $this->db->getRow("select * from #__admin_user where user_id = '{$uid}' and is_deleted = 0");
        if(!$user) {
            return false;
        }
        // check if current user level is still valid in level list
        if($user['level_id']) {
            $isValidCurrentLevel = $this->db->getRow("select * from #__level where level_id = '{$user['level_id']}'");
            if(!$isValidCurrentLevel){
                $updateData = array(
                    "is_disabled" => 1,
                    "access_type" => 'trial',
                    'level_id' => 0,
                    'expired_time' => time(0) - 1
                );
                $user['expired_time'] = 0;
                $this->db->update("#__admin_user", $updateData, "user_id = '{$uid}'");
            }
        }
        // apply new level if current level is expired
        if($user['expired_time'] < time()){
            // select all of level what in range
            $currentDate = date("Y-m-d");
            $lastLevel = $this->db->getRow("select * from #__level where start_date <= '{$currentDate}' and end_date >= '{$currentDate}' and user_id = '{$uid}' order by level_id DESC");

            $data = array("is_disabled" => 1);
            if($lastLevel) {
                $data = array(
                    'is_disabled' => 0,
                    'access_type' => $lastLevel['access_type'],
                    'level_id' => $lastLevel['level_id'],
                    'expired_time' => strtotime($lastLevel['end_date']) + 24 * 60 * 60 - 1
                );
            }
            $this->db->update("#__admin_user", $data, "user_id = '{$uid}'");
        }
        $user = $this->db->getRow("select * from #__admin_user where user_id = '{$uid}'");
        return $user;
    }
}

?>